<?php
$db = new Database();
    $getSettings = $db->query("SELECT * FROM tbsettings");
    foreach($getSettings as $value){
        $Invoice = $value['UpdateInvoice'];
        $Product = $value['UpdateProduct'];
        $logo = $value['logo'];
        $SystemName = $value['SystemName'];
        $footer = $value['footer'];
        $timerU = $value['Time'];
    }
if(isset($_POST['action']))
{
    $auth = Auth::getAuth('current_user');
    $userID = $auth['id'];
    $timezone = "Asia/Manila";
    $time = $auth['userLastLogin']; // User from their record
    //echo $time;
    $timeUpdated_1 = 1; // Set if user has done updating 
    $timeUpdated_0 = 0; // Set if user was nt done updating 
    //  Update scheduler timer
    $datetime = date('Y-m-d H:i'); 
    $new_datetime = date('Y-m-d H:i', strtotime("+$timerU hours", strtotime($datetime))); // Add hour based on user settings set up
    $condition = array("id"=>$userID);
    $fields = array("updated"=>$timeUpdated_0,
                    "updateTime"=>$new_datetime);
        $db->update("tbuser",$fields,$condition);
                                
    
    $login = $db->query("SELECT *
                        FROM tbuser
                        WHERE id={$db->escape($userID)} ","row");
    Auth::setAuth('current_user',$login);
        
    if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);
    if($_POST['action']=="Invoice")
    {
        //variable for alert
        $varAlert = 0; //if 1 success elseif 2 empty elseif 3 wrong format
        $locFile = $_POST['locFile']; // Path Location of the file to be uploaded in the system.
        {
            $destdir = $locFile;
    
            //check if folder location is empty
            $handle = opendir($destdir);
            $c = 0;
            while ($file = readdir($handle)&& $c<3)
            {
                $c++;
            }
            
            if ($c>2)
            {
                $dirs = scandir($locFile);
                    foreach($dirs as $filename)
                    {
                        
                        if (($filename == '.')||($filename == '..'))
                        {
                        }
                        elseif (is_dir($locFile.$filename))
                        {
                            //filesInDir($locFile.'|'.$filename);
                        }
                        else
                        {
                            
                            //$location = $locFile.'/'.$file; // Read the file Location
                            $extension = explode(".", $filename);
                            
                            // Determining if file is already exist or not
                            $getfilename = $db->query("SELECT * FROM tbfname WHERE filename='$filename'","array");
                            foreach($getfilename as $dataFname){
                                $dbFname = $dataFname['filename'];
                            }
                            if($dbFname==$filename){
                                $varAlert = 4;
                            }else{
                                
                                if($extension[1]=="txt")
                                {
                                $location = $locFile.$filename;
                                $loop = 0;
                                $fp = @fopen($location,'r');
                                    while (!feof($fp))
                                    {
                                        $loop++;
                                        $line = fgets($fp,1024); //use 2048 if very long lines
                                        
                                        $field[$loop] = explode (',', $line);
                                        
                                        //28
                                        $file1 = $field[$loop][0];
                                        $file2 = $field[$loop][1];
                                        $file2 = str_replace('"', "", $file2);
                                        $file3 = $field[$loop][2];
                                        $file3 = str_replace('"', "", $file3);
                                        $file4 = $field[$loop][3];
                                        $file4 = str_replace('"', "", $file4);
                                        $file5 = $field[$loop][4];
                                        $file5 = str_replace('"', "", $file5);
                                        $file6 = $field[$loop][5];
                                        $file6 = str_replace('"', "", $file6);
                                        
                                        
                                        $file7 = $field[$loop][6];
                                        $file8 = $field[$loop][7];
                                        $file9 = $field[$loop][8];
                                        $file10= $field[$loop][9];
                                        $file11 = $field[$loop][10];
                                        $file12 = $field[$loop][11];
                                        $file13 = $field[$loop][12];
                                        $file14 = $field[$loop][13];
                                        $file14 = str_replace('"', "", $file14);
                                        $file15 = $field[$loop][14];
                                        $file16 = $field[$loop][15];
                                        $file16 = str_replace('"', "", $file16);
                                        //$file16 = str_replace('0', "", $file16);
                                        //$file_location = $field[$loop][3];
                                        //$file_Name = $field[$loop][4];
                                        $file_uploaded_location = $dest.$file_Name;
                                        $Invoice = array(
                                                        "expiryDate"=>$file1,
                                                        "branchCode"=>$file2,
                                                        "dealerCode"=>$file3,
                                                        "lastName"=>$file4,
                                                        "firstName"=>$file5,
                                                        "middleName"=>$file6,
                                                        "birthdate"=>$file7,
                                                        "appointmentDate"=>$file8,
                                                        "creditLimit"=>$file9,
                                                        "availableLimit"=>$file10,
                                                        "totalAmountDue"=>$file11,
                                                        "nextDueAmount"=>$file12,
                                                        "nextDueDate"=>$file13,
                                                        "InvoiceNo"=>$file14,
                                                        "invoiceDate"=>$file15,
                                                        "pointsEarned"=>$file16,
                                                        "is_active"=>'1'
                                                         );
                                        $affected_record_id = $db->insert("tbdealer",$Invoice);
                                        //$affected_record_id = "";
                                        $audit = array(
                                                       "user_id"=>$userID,
                                                       "action_id"=>1,
                                                       "affected_table"=>"tbdealer",
                                                       "affected_record"=>$affected_record_id,
                                                       "datetime"=>date("Y-m-d  H:i:s"),
                                                       "is_active"=>1
                                                       );
                                        $db->insert("tbaudit_trail",$audit);
                                        
                                           
                                            
                                        $loc = $_POST['locFile'];
                                        $dest = "C:/wamp/www/GS3/Tupperware/gs3_tupperware/images/invoice/";
                                        
                                        copy($loc.$filename, $dest.$filename); // If we copied this successfully, mark it for deletion
                                        $fp++;
                                        //echo "<meta HTTP-EQUIV='REFRESH' content='0; url=documents.php'>";
                                        
                                        // Insert Filename to the database
                                        $insert = array("filename"=>$filename,
                                                        "fileLocation"=>$dest.$filename,
                                                        "dateUploaded"=>date("Y-m-d  H:i:s"),
                                                        "is_active"=>1
                                                        );
                                        $db->insert("tbfname",$insert);
                                        
                                        
                                    }
                                                $audit = array(
                                                    "user_id"=>$userID,
                                                    "action_id"=>2,
                                                    "affected_table"=>"tbproduct",
                                                    "affected_record"=>$affected_record_id,
                                                    "datetime"=>date("Y-m-d  H:i:s"),
                                                    "is_active"=>1
                                                    );
                                        $db->insert("tbaudit_trail",$audit);
                                        
                                        $varAlert = 1;
                                        //echo '<script>alert("Files was successfully uploaded")</script>';
                                        
                                        fclose($fp);
                                        unlink($loc.$filename); // Delete all successfully-copied files
                                }
                                else
                                {
                                    $varAlert = 3;
                                }
                                
                                
                            }
                        }
                    }
            }
            else
            {
                $varAlert = 2;
            } 
        }
    }elseif($_POST['action']=="Product")
    {
        $locFile = $_POST['locFile']; // Path Location of the file to be uploaded in the system.
        $destdir = $locFile;
        //check if folder location is empty
        $handle = opendir($destdir);
        $c = 0;
        while ($file = readdir($handle)&& $c<3)
        {
            $c++;
        }
        
        if ($c>2)
        {
            $dirs = scandir($locFile);
                foreach($dirs as $filename)
                {
                    if (($filename == '.')||($filename == '..'))
                    {
                    }
                    elseif (is_dir($locFile.$filename))
                    {}
                    else
                    {
                        //$location = $locFile.'/'.$file; // Read the file Location
                        $extension = explode(".", $filename);
                        
                        // Determining if file is already exist or not
                        $getfilename = $db->query("SELECT * FROM tbfname WHERE filename='$filename'","array");
                        foreach($getfilename as $dataFname){
                            $dbFname = $dataFname['filename'];
                        }
                        if($dbFname==$filename){
                            $varAlert = 4;
                        }else{
                        
                            if($extension[1]=="csv")
                            {
                            $location = $locFile.$filename;
                            $loop = 0;
                            $fp = @fopen($location,'r');
                            while (!feof($fp))
                            {
                                    
                                $dest=$_POST['location'];
                                
                                
                                   while(($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
                                       $insertProduct = array('itemCode'=>$data[0],
                                                               'product_name'=>$data[1],
                                                               'type'=>$data[3],
                                                               'header'=>$data[2],
                                                               'points'=>$data[4],
                                                               'dateFrom'=>$data[5],
                                                               'date'=>$data[6]);
                                        $db->insert("tbproduct",$insertProduct);
                                    }
                                    
                                $loc = $locFile;
                                $dest = "C:/wamp/www/GS3/Tupperware/gs3_tupperware/images/products/";
        
                                copy($loc.$filename, $dest.$filename); // If we copied this successfully, mark it for deletion
                                $fp++;
                                
                                // Insert Filename to the database
                                        $insert = array("filename"=>$filename,
                                                        "fileLocation"=>$dest.$filename,
                                                        "dateUploaded"=>date("Y-m-d  H:i:s"),
                                                        "is_active"=>1
                                                        );
                                        $db->insert("tbfname",$insert);
                            }
                            
                            $audit = array(
                                        "user_id"=>$userID,
                                        "action_id"=>2,
                                        "affected_table"=>"tbproduct",
                                        "affected_record"=>$affected_record_id,
                                        "datetime"=>date("Y-m-d  H:i:s"),
                                        "is_active"=>1
                                        );
                            $db->insert("tbaudit_trail",$audit);
                            
                            
                            $varAlert = 1;
                                
                                fclose($fp);
                                unlink($loc.$filename); // Delete all successfully-copied files
                            }
                            else
                            {
                                $varAlert = 3;
                            }
                        }
                    }
                }
        }
        else
        {
            $varAlert = 2;
            //echo "Folder location is empty.";
        } 
    }elseif($_POST['action']=="RewardPoints"){
        $locFile = $_POST['locFile']; // Path Location of the file to be uploaded in the system.
        $destdir = $locFile;
        //check if folder location is empty
        $handle = opendir($destdir);
        $c = 0;
        while ($file = readdir($handle)&& $c<3)
        {
            $c++;
        }
        
        if ($c>2)
        {
            $dirs = scandir($locFile);
                foreach($dirs as $filename)
                {
                    if (($filename == '.')||($filename == '..'))
                    {
                    }
                    elseif (is_dir($locFile.$filename))
                    {}
                    else
                    {
                        //$location = $locFile.'/'.$file; // Read the file Location
                        $extension = explode(".", $filename);
                        
                        // Determining if file is already exist or not
                        $getfilename = $db->query("SELECT * FROM tbfname WHERE filename='$filename'","array");
                        foreach($getfilename as $dataFname){
                            $dbFname = $dataFname['filename'];
                        }
                        if($dbFname==$filename){
                            $varAlert = 4;
                        }else{
                        
                            if($extension[1]=="csv")
                            {
                            $location = $locFile.$filename;
                            $loop = 0;
                            $fp = @fopen($location,'r');
                            while (!feof($fp))
                            {
                                    
                                $dest=$_POST['location'];
                                   while(($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
                                       $insertNewDealer = array('expiryDate'=>$data[0],
                                                               'invoiceDate'=>$data[1],
                                                               'dealerCode'=>$data[3],
                                                               'firstName'=>$data[2],
                                                               'lastName'=>$data[4],
                                                               'pointsEarned'=>$data[5]."-|-".$data[6],
                                                               'is_active'=>1);
                                        $db->insert("tbdealer",$insertNewDealer);
                                    }
                                    
                                $loc = $locFile;
                                $dest = "C:/wamp/www/GS3/Tupperware/gs3_tupperware/images/products/";
        
                                copy($loc.$filename, $dest.$filename); // If we copied this successfully, mark it for deletion
                                $fp++;
                                
                                // Insert Filename to the database
                                        $insert = array("filename"=>$filename,
                                                        "fileLocation"=>$dest.$filename,
                                                        "dateUploaded"=>date("Y-m-d  H:i:s"),
                                                        "is_active"=>1
                                                        );
                                        $db->insert("tbfname",$insert);
                            }
                            
                            $audit = array(
                                        "user_id"=>$userID,
                                        "action_id"=>2,
                                        "affected_table"=>"tbproduct",
                                        "affected_record"=>$affected_record_id,
                                        "datetime"=>date("Y-m-d  H:i:s"),
                                        "is_active"=>1
                                        );
                            $db->insert("tbaudit_trail",$audit);
                            
                            
                            $varAlert = 1;
                                
                                fclose($fp);
                                unlink($loc.$filename); // Delete all successfully-copied files
                            }
                            else
                            {
                                $varAlert = 3;
                            }
                        }
                    }
                }
        }
        else
        {
            $varAlert = 2;
            //echo "Folder location is empty.";
        } 
    }
}

if($varAlert==1){
    echo "Files was successfully uploaded.";
}elseif($varAlert==2){
    echo "Folder location is empty.";
}elseif($varAlert==3){
    echo "Invalid File Format.";
}elseif($varAlert==4){
    echo "File is already uploaded.";
}